<?php

class ModelComments
{
	/**
	 * Function to save data
	 */
	public function save()
	{
		$db = JFactory::getDbo();
		$post = JRequest::get('post');
		
		$server = JRequest::get('server');
		$ip = $server['REMOTE_ADDR'];
		
		$user = JFactory::getUser();
		
		$title = (isset($post['title'])) ? $post['title'] : '';
		$username = '';
		$name = (isset($post['fullname'])) ? $post['fullname'] : '';
		$email = (isset($post['email'])) ? $post['email'] : '';
		$userid = '';
		$state = 0;
		
		if($user->id)
		{
			$username = $user->username;
			$name = $user->name;
			$email = $user->email;
			$userid = $user->id;			
		}
		
		$params = JComponentHelper::getParams('com_je_comment');
		if($params->get('auto_approved'))
			$state = 1;
		
		$query = "INSERT INTO #__je_comments SET 
														title = '$title',
														comment = '".$post['comment']."',
														item_id = '".$post['item_id']."',
														component = '".$post['component']."',
														userid = '$userid',
														name = '$name',
														username = '$username',
														email = '$email',
														homepage = '',
														ip = '$ip',
														date = '".date('Y-m-d H:i:s')."',
														state = $state
					";
		
		$db->setQuery($query);
		$db->query();
		
		if($db->getErrorNum())
			return false;
			
		return true;
	}
	
	/**
	 * Function to get list comment
	 * 
	 * @param int 		$itemId			Item ID
	 * @param string 	$component		Component
	 * 
	 * @return list comments
	 */
	function getList($itemId, $component)
	{
		$db = JFactory::getDbo();
		$query = "SELECT * FROM #__je_comments WHERE item_id = '$itemId' AND component = '$component' AND state = 1 ORDER BY id";
		
		$db->setQuery($query);
		$result = $db->loadObjectList();
				
		return $result;
	}
	
	/**
	 * Function to get number of comments
	 * 
	 * @param int 		$itemId			Item ID
	 * @param string 	$component		Component
	 * 
	 * @return number of comments
	 */
	function countComments($itemId, $component)
	{
		$db = JFactory::getDbo();
		$query = "SELECT COUNT(id) as number FROM #__je_comments WHERE item_id = '$itemId' AND component = '$component' AND state = 1";
		
		$db->setQuery($query);
		return $db->loadResult();
	}
}